/**
 * WordTest.java [V 1.0.0]
 * classes : com.xiaocq.wordsgod.WordTest
 * xiaocq Create at 2012-7-14 下午3:36:30
 */
package com.xiaocq.wordsgod;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaocq.wordsgod.db.DataGenerateCenter;
import com.xiaocq.wordsgod.model.Control;
import com.xiaocq.wordsgod.model.Vocabulary;

/**
 * com.xiaocq.wordsgod.WordTest
 * 
 * @author Mystory Create at 2012-7-14 下午3:36:30
 */
public class WordTest extends Activity {
	private Control mControl;
	private List<Vocabulary> wordList;
	private boolean testType;
	private int listPosition = 0;

	/* 公用 */
	private LinearLayout navigator;
	private Button backToMenu;
	private Chronometer chronometer;
	private TextView title;
	private long startTimeInMillis, finishTimeInMillis;

	/* 选择 */
	private Button[] items;
	private TextView displayWord;

	/* 填空 */
	private Button nextOne;
	private EditText input;
	private EditText displayChinese;

	private OnClickListener choiceListener, complectionListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();
		mControl = Control.convertToControl(intent);

		// 获取测试类型，根据测试类型选择要加载的layout
		testType = mControl.getTestType();

		if (testType == Control.CHOICE) {
			initChoiceTest();
		} else {
			initCompletionTest();
		}

		/* 启动单词组装 */
		WrapTask wrapTask = new WrapTask();
		wrapTask.execute();
	}

	/* 初始化选择测试 */
	private void initChoiceTest() {
		setContentView(R.layout.choice);
		navigator = (LinearLayout) findViewById(R.id.choice_navigator);
		displayWord = (TextView) findViewById(R.id.choice_display);

		initCommon();

		items = new Button[4];
		items[0] = (Button) findViewById(R.id.choice_itemA);
		items[1] = (Button) findViewById(R.id.choice_itemB);
		items[2] = (Button) findViewById(R.id.choice_itemC);
		items[3] = (Button) findViewById(R.id.choice_itemD);

		choiceListener = new OnClickListener() {
			public void onClick(View v) {
				pauseCount();

				boolean result = (Boolean) v.getTag();
				long timeCost = getTimeCost();

				mControl.recordResult(result, timeCost);

				// 如果测试完毕，跳转
				if (mControl.getRestTestNum() == 0) {
					sendToResult();
				} else {
					displayChoice();
				}
			}
		};
		for (int i = 0; i < 4; i++) {
			items[i].setOnClickListener(choiceListener);
		}
	}

	/* 初始化填空题测试 */
	private void initCompletionTest() {
		setContentView(R.layout.completion);
		navigator = (LinearLayout) findViewById(R.id.completion_navigator);
		displayChinese = (EditText) findViewById(R.id.completion_display);

		initCommon();

		input = (EditText) findViewById(R.id.completion_input);
		nextOne = (Button) findViewById(R.id.completion_next_one);

		complectionListener = new OnClickListener() {
			public void onClick(View v) {
				pauseCount();

				String[] correct = ((String) v.getTag()).split("\\|");
				String answer = input.getText().toString().trim();
				boolean result = true;
				long timeCost = getTimeCost();

				for (String element : correct) {
					if (element.equals(answer) == false) {
						result = false;
					}
				}
				System.out.println(answer + "   " + correct[0] + result);
				mControl.recordResult(result, timeCost);

				// 如果测试完毕，则跳转
				if (mControl.getRestTestNum() == 0) {
					sendToResult();
				} else {
					displayCompletion();
				}
			}
		};

		nextOne.setOnClickListener(complectionListener);
	}

	/* 初始化公共测试 */
	private void initCommon() {
		backToMenu = (Button) navigator.findViewById(R.id.cnav_leftBtn);
		title = (TextView) navigator.findViewById(R.id.cnav_middleText);
		chronometer = (Chronometer) navigator.findViewById(R.id.cnav_rightBtn);

		backToMenu.setText(R.string.backToMenu);
		backToMenu.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				saveAndQuit();
			}
		});
	}

	private long getTimeCost() {
		return finishTimeInMillis - startTimeInMillis;
	}

	private class WrapTask extends AsyncTask<Void, Integer, Void> {
		private int size = mControl.getRestTestNum();
		private int index = 0;
		private int testedNum;
		private int[] wordScore;

		private ProgressDialog progressDialog;
		private DataGenerateCenter dataGenerateCenter;

		@Override
		protected Void doInBackground(Void... params) {
			dataGenerateCenter.createCursor();

			Vocabulary vocabulary;
			while (index < size) {
				vocabulary = dataGenerateCenter.wrapVocabulary(wordScore[index
						+ testedNum], testType);
				wordList.add(vocabulary);
				index++;
				publishProgress(index);
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dataGenerateCenter = new DataGenerateCenter(mControl, WordTest.this);

			wordList = new ArrayList<Vocabulary>(size);
			wordScore = mControl.getWordScore();
			testedNum = mControl.getTestedNum();

			progressDialog = new ProgressDialog(WordTest.this);
			progressDialog.setMessage(getText(R.string.i_am_loading));
			progressDialog.setMax(size);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setCancelable(false);
			progressDialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			dataGenerateCenter.close();
			if (testType == Control.CHOICE) {
				displayChoice();
			} else {
				displayCompletion();
			}
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			progressDialog.setProgress(values[0]);
		}

	}

	private void displayChoice() {
		Vocabulary vocabulary;
		vocabulary = wordList.get(listPosition++);
		String[] chinese = vocabulary.getChinese();
		int id = vocabulary.getId();
		displayWord.setText(vocabulary.getEnglish());
		for (int i = 0; i < 4; i++) {
			items[i].setText(chinese[i]);
			if (i == (id % 4)) {
				items[i].setTag(true);
			} else {
				items[i].setTag(false);
			}
		}

		setProcess();
	}

	private void displayCompletion() {
		Vocabulary vocabulary;
		vocabulary = wordList.get(listPosition++);
		String[] chinese = vocabulary.getChinese();
		String english = vocabulary.getEnglish();

		input.setText("");
		displayChinese.setText(chinese[0]);
		nextOne.setTag(english);

		setProcess();
	}

	private void setProcess() {
		String process = mControl.getTestedNum() + 1 + " / "
				+ mControl.getTotalNum();
		title.setText(process);

		startCount();
	}

	private void startCount() {
		startTimeInMillis = SystemClock.elapsedRealtime();
		chronometer.setBase(startTimeInMillis);
		chronometer.start();
	}

	private void pauseCount() {
		
		try {
			Thread.sleep(100);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		finishTimeInMillis = SystemClock.elapsedRealtime();
		chronometer.setBase(finishTimeInMillis);
	}

	private void saveAndQuit() {
		mControl.saveToXml(getSharedPreferences(Control.PREF_NAME,
				Context.MODE_PRIVATE));
		Toast.makeText(WordTest.this, R.string.processSaved, 1000).show();

		finish();
	}

	private void sendToResult() {
		mControl.setNewTest(false);
		Intent intent = mControl.convertToIntent();
		intent.setClass(WordTest.this, Result.class);
		startActivity(intent);
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			saveAndQuit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
